package com.panda.bbs.controller;

import com.panda.bbs.domain.Post;
import com.panda.bbs.domain.User;
import com.panda.bbs.service.IPostService;
import com.panda.bbs.service.IUserService;
import com.panda.bbs.service.impl.PostServiceImpl;
import com.panda.bbs.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    private IUserService userService = new UserServiceImpl();
    private IPostService postService = new PostServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String method = request.getParameter("method");
        if(method.equals("login")){
            // 登录请求
            login(request, response);
        }else if(method.equals("register")){
            // 注册请求
            register(request, response);
        } else if(method.equals("logout")){
            // 注销请求
            logout(request, response);
        }else if(method.equals("getUserByUserId")){
            // 根据用户ID获取用户
            getUserByUserId(request, response);
        }else if(method.equals("getUserAndPostByUserId")){
            // 根据用户ID获取用户信息&用户所有文章
            getUserAndPostByUserId(request, response);
        }else if(method.equals("modifyUser")){
            // 修改个人信息
            modifyUser(request, response);
        }
    }
    // 根据用户ID获取用户
    public void getUserByUserId(HttpServletRequest request, HttpServletResponse response){
        String userId = request.getParameter("userId");
        User user = userService.getUserByUserId(userId);
        request.setAttribute("user",user);
        try {
            request.getRequestDispatcher("/WEB-INF/pages/user/user.jsp").forward(request,response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 根据用户ID获取用户信息&用户所有文章
    public void getUserAndPostByUserId(HttpServletRequest request, HttpServletResponse response){
        String userId = request.getParameter("userId");
        // 获取用户信息
        User user = userService.getUserByUserId(userId);
        // 获取用户的所有文章
        List<Post> userPostList= postService.getPostByAuthorId(userId);
        request.setAttribute("user",user);
        request.setAttribute("userPostList",userPostList);
        try {
            request.getRequestDispatcher("/WEB-INF/pages/user/user.jsp").forward(request,response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    // 修改用户信息
    public void modifyUser(HttpServletRequest request, HttpServletResponse response){
        User user = (User) request.getSession().getAttribute("user");
        // 获取表单数据
        String username = request.getParameter("username");
        String gender = request.getParameter("sex");
        String email = request.getParameter("email");
        String phoneNumber = request.getParameter("phoneNumber");
        String location = request.getParameter("city");
        String bio = request.getParameter("sign");
        // 设置表单数据
        user.setUsername(username);
        user.setGender(gender);
        user.setEmail(email);
        user.setPhoneNumber(phoneNumber);
        user.setLocation(location);
        user.setBio(bio);
        userService.editProfile(user);
        try {
            // 获取用户的所有文章
            List<Post> userPostList= postService.getPostByAuthorId(user.getUserId());
            request.setAttribute("user",user);
            request.setAttribute("userPostList",userPostList);
            request.getRequestDispatcher("/WEB-INF/pages/user/user.jsp").forward(request,response);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }

    }
    // 登录请求
    public void login(HttpServletRequest request, HttpServletResponse response){
        User user = null;
        // 获取用户输入信息
        String userInput = request.getParameter("userInput");
        String password = request.getParameter("pass");
        String verifyCode = request.getParameter("vercode");
        String checkCode = String.valueOf(request.getSession().getAttribute("verifyCode"));
        try {
            // 登录验证
            if(userInput != null && !userInput.equals("") && password != null && !password.equals("") && verifyCode != null && !verifyCode.equals("")){
                if(userInput.matches("^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$")){
                    // 正则匹配邮箱，验证码
                    if(verifyCode.equalsIgnoreCase(checkCode)){
                        user = userService.getUserByEmailAndPassword(userInput,password);
                        if(user != null){
                            System.out.println("登录成功");
                            request.getSession().setAttribute("user",user);
                            request.getRequestDispatcher("/index.jsp").forward(request,response);
                        }else{
                            System.out.println("登陆失败，密码错误");
                            response.getWriter().write("登录失败,密码错误");
                        }
                    }else{
                        System.out.println("验证码输入有误");
                        response.getWriter().write("验证码输入有误");
                    }
                }else if(userInput.matches("^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$")){
                    // 正则匹配手机号，验证码
                    if(verifyCode.equalsIgnoreCase(checkCode)){
                        user = userService.getUserByPhoneNumberAndPassword(userInput,password);
                        if(user != null){
                            System.out.println("登录成功");
                            request.getSession().setAttribute("user",user);
                            request.getRequestDispatcher("/index.jsp").forward(request,response);
                        }else{
                            System.out.println("登陆失败，密码错误");
                            response.getWriter().write("登录失败,密码错误");
                        }
                    }else{
                        System.out.println("验证码输入有误");
                        response.getWriter().write("验证码输入有误");
                    }
                }else{
                    System.out.println("请输入正确的手机/邮箱");
                    response.getWriter().write("请输入正确的手机/邮箱");
                }
            }else{
                System.out.println("输入为空！");
                response.getWriter().write("输入为空！");
            }

        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 注册请求
    public void register(HttpServletRequest request, HttpServletResponse response){
        String userId = String.valueOf(UUID.randomUUID());
        String username = request.getParameter("username");
        String password = request.getParameter("pass");
        String confirmPassword = request.getParameter("repass");
        String email = request.getParameter("email");
        String phoneNumber = request.getParameter("phoneNumber");
        String avatar = "default.png";
        String joinTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String verifyCode = request.getParameter("vercode");
        String checkCode = String.valueOf(request.getSession().getAttribute("verifyCode"));
        try {
            if(username != null && password != null && confirmPassword != null && email != null && phoneNumber != null){
                if(!userService.isExistingUsername(username)){
                    if(confirmPassword.equals(password)){
                        if(!userService.isExistingEmail(email)){
                            if(!userService.isExistingPhoneNumber(phoneNumber)){
                                if(verifyCode.equalsIgnoreCase(checkCode)){
                                    User user = new User(userId,username,password,email,phoneNumber,avatar,null,joinTime,null,null,null,null);
                                    userService.register(user);
                                    System.out.println("注册成功，前往登录！");
                                    response.getWriter().write("注册成功，前往登录！");
                                    request.getRequestDispatcher("/WEB-INF/pages/user/login.jsp").forward(request,response);
                                }else{
                                    System.out.println("验证码有误");
                                    response.getWriter().write("验证码有误");
                                }
                            }else{
                                System.out.println("手机号已被注册");
                                response.getWriter().write("手机号已被注册");
                            }
                        }else{
                            System.out.println("邮箱已存在");
                            response.getWriter().write("邮箱已存在");
                        }
                    }else{
                        System.out.println("两次密码不一致");
                        response.getWriter().write("两次密码不一致");
                    }
                }else{
                    System.out.println("用户名已存在");
                    response.getWriter().write("用户名已存在");
                }
            }
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 注销请求
    public void logout(HttpServletRequest request, HttpServletResponse response){
        request.getSession().removeAttribute("user");
        try {
            request.getRequestDispatcher("/index.jsp").forward(request,response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
